using Godot;
using System.Collections.Generic;


[GlobalClass]
public partial class StateMachine : Node
{
    private bool _active = true;
    private readonly Dictionary<StringName, State> _statesDict = new();

    [Export] public CanvasItem Target { get; set; }
    [Export] public AnimationPlayer AmtPlayer { get; set; }
    [Export] public AnimationTree AmtTree { get; set; }
    [Export] public State CurrState { get; set; }
    [Export] public bool Active
    {
        get { return _active; }
        set
        {
            _active = value;
            SetProcess(_active);
            SetPhysicsProcess(_active);
            SetProcessUnhandledInput(_active);
        }
    }

    public override void _Ready()
    {
        foreach(var node in GetChildren())
        {
            if (node is not State) continue;
            (node as State).Switch += SwitchState;
            _statesDict[node.Name] = node as State;

            if (CurrState == null)
            {
                CurrState = node as State;
            }

            SwitchState(CurrState.Name);
        }
    }

    public override void _Process(double delta)
    {
        base._Process(delta);
        CurrState?.Update(delta);
    }

    public override void _PhysicsProcess(double delta)
    {
        base._PhysicsProcess(delta);
        CurrState?.FixedUpdate(delta);
    }

    public override void _UnhandledInput(InputEvent @event)
    {
        base._UnhandledInput(@event);
        CurrState?.HandleInput(@event);
    }

    public void SwitchState(StringName name)
    {
        if (!_active || CurrState == null) return;

        CurrState.Exit();
        CurrState = _statesDict[name];
        CurrState.Enter();
    }
}
